package com.xiaoma.tpo.web;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.xiaoma.tpo.dao.DownloadApkDao;
import com.xiaoma.tpo.domain.DownloadApk;

@Controller
@RequestMapping("/download")
public class DownloadAPKController {
    private static final Logger LOG = LoggerFactory.getLogger(DownloadAPKController.class);
    private static final int[] WAYS = {1,2,3,4,5};
    private static final String URL = "http://tpopro.b0.upaiyun.com/tpo_apk/xiaomaguohe_tpo.apk";
    
    @Autowired
    private DownloadApkDao apkDao;
    
    
    @RequestMapping(value="/apk/{way}", method = RequestMethod.GET)
    public void downloadAPK(HttpServletResponse response, @PathVariable Integer way) {
        if (Arrays.binarySearch(WAYS, way) >= 0) {
            DownloadApk entity = new DownloadApk();
            entity.setWay(way);
            List<DownloadApk> apks = apkDao.findByColumns(entity);
            if (apks.size() > 0) {
                DownloadApk apk = apks.get(0);
                apk.setCount(apk.getCount() + 1);
                apkDao.update(apk);
            } else {
                DownloadApk downloadApk = new DownloadApk();
                downloadApk.setCount(1);
                downloadApk.setWay(way);
                apkDao.insert(downloadApk);
            }
            
            try {
                response.sendRedirect(URL);
            } catch (IOException e) {
                e.printStackTrace();
                LOG.error("apk download failed: " + e);
            }
        } else {
            LOG.error("invalid way code: " + way);
        }
        
    }

}
